package cn.aicnn.chatssespringboot.service.Impl;

import cn.aicnn.chatssespringboot.common.CommonResponse;
import cn.aicnn.chatssespringboot.dto.Chat;
import cn.aicnn.chatssespringboot.dto.Dialog;
import cn.aicnn.chatssespringboot.persistence.chatMapper;
import cn.aicnn.chatssespringboot.persistence.dialogMapper;
import cn.aicnn.chatssespringboot.service.ChatService;
import cn.aicnn.chatssespringboot.vo.DialogVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.aicnn.chatssespringboot.persistence.chatMapper;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    chatMapper chatMapper;
    @Autowired
    dialogMapper dialogMapper;
    @Override
    public int insertChat(String question, String userId) {
        //需要插入的chatId
        int id = 0;
        Long chatId = chatMapper.selectCount(null);
        //当表内数据不为空的情况
        if (chatId.intValue() != 0){
            //获取id最大值
            QueryWrapper<Chat> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("id").last("LIMIT 1");
            Chat chat = chatMapper.selectOne(queryWrapper);
            id = chat.getId() + 1;
        }

        System.out.println("id:"+id);

        //新建chat对象，确定ChatId
        Chat chat = new Chat();
        chat.setId(id);
        chat.setName(question);
        chat.setUser(userId);
        LocalDate today = LocalDate.now();
        chat.setDate(Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        chatMapper.insert(chat);

        return id;
    }

    @Override
    public CommonResponse<Object> changeTitle(int chatId, String name) {
        int result = chatMapper.updateNameByChatId(chatId, name);
        if (result > 0) {
            return CommonResponse.createForSuccess("SUCCESS");
        }
        return CommonResponse.createForError("ERROR");
    }

    @Override
    public CommonResponse<Object> deleteChat(int chatid) {
        int result = chatMapper.deleteChat(chatid);
        if (result > 0){
            return CommonResponse.createForSuccess("SUCCESS");
        }
        return CommonResponse.createForError("ERROR");
    }

    @Override
    public CommonResponse<List<Dialog>> getDialog(int chatid) {
        List<Dialog> dialogList = dialogMapper.getDialog(chatid);
        if (!dialogList.isEmpty()){
            return CommonResponse.createForSuccess("SUCCESS", dialogList);
        }
        return CommonResponse.createForError("ERROR");
    }

    @Override
    public CommonResponse<List<DialogVO>> getChatList(String username) {
        List<DialogVO> resultList = new ArrayList<>();
        List<Chat> chatList = chatMapper.getList(username);

        // 将 chatList 按照日期递减排序
        chatList.sort(Comparator.comparing(Chat::getDate).reversed());

        //标志位，防止重插标签
        boolean todayAdded = false;
        boolean yesterdayAdded = false;
        boolean last7DaysAdded = false;
        boolean last30DaysAdded = false;
        boolean earlierAdded = false;

        for(Chat chat: chatList){
            DialogVO dialogVO = new DialogVO();
            dialogVO.setChatId(chat.getId());
            dialogVO.setName(chat.getName());

            Date today = new Date();
            Date date = chat.getDate();

            int intervalDays = getDifferenceInDays(today, date);
            //进行时间分类，今天，昨天，前7天，前30天，更早
            if(intervalDays == 0 && !todayAdded){
                resultList.add(createLabelVO("今天"));
                todayAdded = true;
            } else if(intervalDays == 1 && !yesterdayAdded){
                resultList.add(createLabelVO("昨天"));
                yesterdayAdded = true;
            } else if(intervalDays > 1 && intervalDays <= 7 && !last7DaysAdded){
                resultList.add(createLabelVO("前7天"));
                last7DaysAdded = true;
            } else if(intervalDays > 7 && intervalDays <= 30 && !last30DaysAdded){
                resultList.add(createLabelVO("前30天"));
                last30DaysAdded = true;
            } else if(intervalDays > 30 && !earlierAdded){
                resultList.add(createLabelVO("更早"));
                earlierAdded = true;
            }

            resultList.add(dialogVO);
        }
        return CommonResponse.createForSuccess("SUCCESS", resultList);
    }

    private DialogVO createLabelVO(String label){
        DialogVO labelVO = new DialogVO();
        labelVO.setChatId(-1);
        labelVO.setName(label);
        return labelVO;
    }

    public static int getDifferenceInDays(Date date1, Date date2) {
        long diffInMillis = Math.abs(date1.getTime() - date2.getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
        return (int) diffInDays;
    }

}
